__author__ = 'RemiZOffAlex'
__email__ = 'remizoffalex@mail.ru'

import jinja2
import pathlib
import aiohttp_jinja2

from aiohttp.web import View, Response

from .. import JSONRPC


pathlib.Path(__file__).parent.resolve()

class APIHandler:
    def __init__(self, jsonrpc):
        print(self)
        self.jsonrpc = jsonrpc

    @aiohttp_jinja2.template('api_browse.html')
    async def get(self, request) -> Response:
        pagedata = {
            'title': 'API Browse',
            'request': request
        }
        return pagedata

    async def post(self, request) -> Response:
        json_data = await request.json()
        result = jsonrpc(json_data)
        return Response(result=result)


def api_init(app, jsonrpc: JSONRPC, rule: str = '/api'):
    aiohttp_jinja2.setup(
        app,
        enable_async=True,
        loader=jinja2.FileSystemLoader(
            pathlib.Path(__file__).parent.resolve() / 'templates'
        )
    )
    handler = APIHandler(jsonrpc)
    app.router.add_route('GET', rule, handler.get)
    app.router.add_route('POST', rule, handler.post)
